/*******************************************************************************
 * $Header$
 * $Revision$
 * $Date$
 *
 *==============================================================================
 *
 * Copyright©hxlife/hulife 
 * All rights reserved.
 * 
 * Created on 2018年5月9日
 *******************************************************************************/

package com.hualife.md.common.service.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.hualife.md.common.dao.mybatis.entity.DefKv;
import com.hualife.md.common.dao.mybatis.mapper.DefKvMapper;
import com.hualife.md.common.dto.wx.user.WeChatUserGetResponseDTO;
import com.hualife.md.common.service.IWeChatUserService;
import com.hualife.support.exception.BusinessException;
import com.hualife.support.exception.SysException;
import com.hualife.support.util.HttpUtil;
import com.hualife.support.util.JsonUtil;

/**
 * @description: TODO 此处填写 class 信息
 * @author 孙小冬 (mailto:sunxiaodong001@hualife.cc)
 */
@Service("weChatUserService")
public class WeChatUserServiceImpl implements IWeChatUserService {
	private static final Logger logger = LoggerFactory
			.getLogger(WeChatUserServiceImpl.class);

	@Autowired
	private DefKvMapper defKvMapper;

	private static final String WECHAT_USER_GET = "wx.user.get";

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.hualife.md.common.service.IWeChatUserService#queryUser(java.lang.
	 * String, java.lang.String)
	 */
	@Override
	public WeChatUserGetResponseDTO queryUser(String userId, String token) {
		DefKv kv = defKvMapper.selectByPrimaryKey(WECHAT_USER_GET);
		if (kv == null) {
			throw new SysException("读取用户失败，未查询到从企业号读取成员的配置信息");
		}

		try {
			String url = kv.getV() + "?access_token=" + token + "&userid="
					+ userId;
			String resultJson = HttpUtil.get(url);
			if (resultJson == null || "".equals(resultJson.trim())) {
				throw new BusinessException("读取用户失败，企业号未返回数据！");
			}
			WeChatUserGetResponseDTO result = new WeChatUserGetResponseDTO();
			result = (WeChatUserGetResponseDTO) JsonUtil.SnakeJson2CamelBean(
					resultJson, WeChatUserGetResponseDTO.class);
			return result;
		} catch (Exception e) {
			logger.error("读取用户失败，请求异常【{}】", e.getMessage());
			e.printStackTrace();
			throw new BusinessException("读取用户失败，原因是：" + e.getMessage());
		}
	}

}

/*
 * 修改历史 $Log$
 */